﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using publicLibrary;

namespace asMeishi.web.Models
{
    /*
     * IActionFilter(Action拦截器接口)
     * 2个方法 OnActionExecuting OnActionExecuted
     * Action拦截器分别在“执行Action之前”拦截和“执行Action之后”拦截
     * 
     * IResultFilter(Result拦截器接口)
     * 2个方法 OnResultExecuting OnResultExecuted
     * IResultFilter 执行前和执行后，分别是在 返回Result之前执行和返回Result之后执行。
     * 
     * 顺序是：OnActionExecuting-->Action中的代码-->OnActionExecuted-->OnResultExecuting-->OnResultExecuted
     * 
     * IExceptionFilter(异常拦截器接口)
     * 一个方法，就是当异常发生时需要执行的内容 OnException
     * 
     * IAuthorizationFilter(授权拦截器接口)
     * 用来判断权限，判断时候有权限执行后面的Action，此接口在任何拦截器之前执行
     * OnAuthorization
     * 
     */

    public class authorityFilter : FilterAttribute, IActionFilter//FilterAttribute, IActionFilter, IResultFilter, IExceptionFilter, IAuthorizationFilter
    {
        level level;
        //actions action;
        actionEnum action;
        authorityReturn re;
        user user;

        /// <summary>
        /// 是否需要进行返回视图后的 后续处理
        /// </summary>
        //bool isExecuted = false;

        actionTypeEnum type;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="action"></param>
        public authorityFilter(actionEnum action, actionTypeEnum type = actionTypeEnum.json)
        {
            //得到动作
            //this.actions = new MongoSession<actions>().Get(d => d.action == action);
            this.action = action;

            //得到用户等级
            level = userC.userLevel;

            //得到用户
            user = userC.loginUser;

            this.type = type;
        }

        #region IActionFilter 成员

        /// <summary>
        /// 执行Action之前
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            init();
            //管理员权限
            if (action == actionEnum.manage)
            {
                if (user.group != "100")
                {
                    re = new authorityReturn("error", "满足不了您的要求，sorry");
                    filterContext.HttpContext.Response.Write(re.json());
                    filterContext.HttpContext.Response.End();
                    //isExecuted = false; //不需要处理
                    filterContext.Result = new EmptyResult();//赋一个不等于null的值来阻止继续执行
                    return;
                }
            }
            else
            {
                //判断是否允许该动作
                if (!level.isPassAction(action))
                {
                    re = new authorityReturn("error", "您的等级不允许进行此操作！");
                    var restr = "";

                    switch (type)
                    {
                        case actionTypeEnum.str:
                            restr = re.str();
                            break;
                        case actionTypeEnum.json:
                            restr = re.json();
                            break;
                        default:
                            break;
                    }
                    filterContext.HttpContext.Response.Write(restr);

                    filterContext.HttpContext.Response.End();
                    //isExecuted = false; //不需要处理
                    filterContext.Result = new EmptyResult();//赋一个不等于null的值来阻止继续执行
                    return;
                }

                //判断MP值
                if (user.mp - asMeishi.web.MvcApplication.getActionsApplication(action).decreaseMp < 0)
                {
                    re = new authorityReturn("error", "您的MP值不足！");
                    filterContext.HttpContext.Response.Write(re.json());
                    filterContext.HttpContext.Response.End();
                    //isExecuted = false; //不需要处理
                    filterContext.Result = new EmptyResult();//赋一个不等于null的值来阻止继续执行
                    return;
                }
            }

            //isExecuted = true; //需要处理

        }

        /// <summary>
        /// 执行Action之后
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (action == actionEnum.manage) { return; }
            //if (!isExecuted) return;

            //进行加减分处理
            user.hp += asMeishi.web.MvcApplication.getActionsApplication(action).gainHp;
            user.mp -= asMeishi.web.MvcApplication.getActionsApplication(action).decreaseMp;
            user.experience += asMeishi.web.MvcApplication.getActionsApplication(action).experience;

            //数据库更新&写session
            userC.update(user);

        }

        #endregion

        #region IResultFilter 成员

        /// <summary>
        /// 返回Result之前
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            //filterContext.RequestContext.HttpContext.Response.Write("Result执行之前!");
        }

        /// <summary>
        /// 返回Result之后
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            //filterContext.RequestContext.HttpContext.Response.Write("Result已经执行了!");
        }

        #endregion

        #region IExceptionFilter 成员

        /// <summary>
        /// 异常发生时
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnException(ExceptionContext filterContext)
        {
            //string controller = filterContext.RouteData.Values["controller"] as string;
            //string action = filterContext.RouteData.Values["action"] as string;
            //filterContext.RequestContext.HttpContext.Response.Write(string.Format("{0}:{1}发生异常!{2}", controller, action, filterContext.Exception.Message));
            //filterContext.ExceptionHandled = true;
        }

        #endregion

        #region IAuthorizationFilter 成员

        /// <summary>
        /// 判断权限
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //filterContext.HttpContext.Response.Write("执行authorization! 判断时候有权限。。。。<br />");
        }

        #endregion

        /// <summary>
        /// 返回的数据类
        /// </summary>
        public class authorityReturn
        {
            public string code;
            public string info;
            public string more;

            public authorityReturn(string code = "ok", string info = "处理成功", string more = "")
            {
                this.code = code;
                this.info = info;
                this.more = more;
            }

            public string json()
            {
                return publicLibrary.AjaxCallBackInfo.json(code, info, more);
            }

            public string xml()
            {
                //待编...
                return @"<root></root>";
            }

            public string str()
            {
                return string.Format("{0}|{1}|{2}", code, info, more);
            }

        }

        void init()
        {
            //得到用户等级
            level = userC.userLevel;

            //得到用户
            user = userC.loginUser;
        }


    }
    /// <summary>
    /// 验证权限可用性
    /// </summary>
    public static class powerCheck
    {
        public static bool recordEditDel(string userId, user loginUser)
        {
            if (loginUser.limit > 100) { return true; }
            if (userId == null) { return false; }
            if (userId == loginUser.Id.ToTryString()) { return true; }
            return false;
        }
    }
}